package com.gulimall.order.web;

import com.gulimall.common.utils.PageUtils;
import com.gulimall.order.service.OrderService;
import com.gulimall.order.vo.OrderConfirmVo;
import com.gulimall.order.vo.OrderSubmitResponseVo;
import com.gulimall.order.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Map;

/**
 * @author kkk
 * @date 2022/8/3
 */
@Controller
public class OrderWebController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public Object toTrade(Model model) {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        System.out.println(confirmVo);
        model.addAttribute("orderConfirmData", confirmVo);
        return "settlement";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        OrderSubmitResponseVo responseVo = orderService.submitOrder(orderSubmitVo);
        System.out.println(responseVo);
        //下单失败回到订单页重新确认订单消息
        if (responseVo.getCode() == 0) {
            //下单成功来到支付选择页
            model.addAttribute("orderResp", responseVo);
            return "pay";
        } else {
            switch (responseVo.getCode()) {
                case 1:
                    redirectAttributes.addAttribute("msg", "订单令牌已过期，请刷新页面重试");
                    break;
                case 2:
                    redirectAttributes.addAttribute("msg", "商品价格异常");
                    break;
                case 3:
                    redirectAttributes.addAttribute("msg", "商品库存异常");
                    break;
                default:
                    break;
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }

    @GetMapping("/order.html")
    public String orderList(@RequestParam Map<String, Object> params, Model model) {
        PageUtils page = orderService.getOrderList(params);

        model.addAttribute("page", page);
        return "order";
    }
}
